const state = {
  notification: {
    visible: true,
    sender: '系统消息',
    content: '您有一条新消息',
    avatar: '/static/logo.png',
    senderId: null
  }
};

const mutations = {
  SET_NOTIFICATION: (state, notification) => {
    state.notification = { ...state.notification, ...notification };
  },
  SHOW_NOTIFICATION: (state) => {
    state.notification.visible = true;
  },
  HIDE_NOTIFICATION: (state) => {
    state.notification.visible = false;
  }
};

const actions = {
  // 显示通知
  showNotification({ commit }, notification) {
    commit('SET_NOTIFICATION', notification);
    commit('SHOW_NOTIFICATION');
    
    // 自动隐藏通知
    setTimeout(() => {
      commit('HIDE_NOTIFICATION');
    }, 5000);
  },
  
  // 隐藏通知
  hideNotification({ commit }) {
    commit('HIDE_NOTIFICATION');
  },
  
  // 处理WebSocket消息
  handleWebSocketMessage({ commit, rootState }, data) {
    try {
      // 解析消息数据
      const message = JSON.parse(data);
      
      // 获取当前页面路径
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage ? currentPage.route : '';
      
      // 如果当前在聊天页面，且正在和消息发送者聊天，不显示通知
      const isInChatPage = currentRoute === 'pages/consultation/chat';
      const currentChatDoctorId = rootState.app.currentChatDoctorId;
      const chatWithSender = currentChatDoctorId == message.senderId;
      console.log(currentChatDoctorId);
	  console.log(chatWithSender);
      if (isInChatPage && chatWithSender) {
        // 直接通过页面的方法处理消息
        if (currentPage && typeof currentPage.handleWebSocketMessage === 'function') {
          currentPage.handleWebSocketMessage(data);
        }
        return;
      }
      
      // 否则显示通知
      const notification = {
        sender: message.senderName || '医生',
        content: message.content || '您有一条新消息',
        avatar: message.senderAvatar || '/static/logo.png',
        senderId: message.senderId,
        visible: true
      };
      
      commit('SET_NOTIFICATION', notification);
      commit('SHOW_NOTIFICATION');
      
      // 播放提示音
      if (typeof plus !== 'undefined') {
        try {
          plus.device.beep(1);
        } catch (error) {
          console.error('播放提示音失败:', error);
        }
      }
      
      // 自动隐藏通知
      setTimeout(() => {
        commit('HIDE_NOTIFICATION');
      }, 5000);
    } catch (error) {
      console.error('处理WebSocket消息出错:', error);
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}; 